(function () {
  layui.use(["table", "element", "form", "laydate", "upload"], function () {
    var table = layui.table;
    var element = layui.element;
    var form = layui.form;
    var laydate = layui.laydate;
    var upload = layui.upload;
    var $ = layui.jquery;
    var bid = "";
    let type = "";

    var suid = localStorage.getItem("suid");

    //日期范围
    laydate.render({
      elem: "#date",
      range: true,
      done: function (value, date, endDate) {
        var beginTime = value.substring(0, 10);
        var endTime = value.substring(13);
        if (beginTime && endTime) {
          table.reload(
            "reloadTable",
            {
              page: {
                curr: 1, //重新从第 1 页开始
              },
              where: {
                beginTime: new Date(beginTime),
                endTime: new Date(endTime),
              },
            },
            "data"
          );
        } else {
          location.reload();
        }
      },
    });

    //普通图片上传
    upload.render({
      elem: "#uploadImg",
      url: GlobalSiteUrl + "/img/banner", //改成您自己的上传接口
      auto: false,
      bindAction: "#submit",
      acceptMime: "image/*",
      before: function (obj) {
        //预读本地文件示例，不支持ie8
        obj.preview(function (index, file, result) {
          $("#img").attr("src", result); //图片链接（base64）
        });
        var suid = localStorage.getItem("suid");
        var FromData = $(".addForm").serializeArray();
        this.data = { suid, text: FromData[0].value, sid:FromData[1].value, bid, type };
        console.log(this.data);
      },
      done: function (res) {
        layer.msg(res.msg);
        setTimeout(function () {
          location.reload();
        }, 1500);
      },
      error: function () {},
    });

    //第一个实例
    table.render({
      elem: "#table",
      toolbar: "#toolbarDemo",
      width: "auto",
      height: "full - 100",
      url: GlobalSiteUrl + "/img/selectBanners", //数据接口
      response: {
        statusCode: 200, //重新规定成功的状态码为 200，table 组件默认为 0
      },
      parseData: function (res) {
        if (res.data == null) {
          alert(res.msg);
          location.reload();
          return;
        } else {
          var data = res.data.list;
          data.forEach((element) => {
            element["create_time"] = formatTime(element["create_time"]);
            element["update_time"] = !element["update_time"]
              ? "暂未更新"
              : formatTime(element["update_time"]);
          });
          if (res.data.total === 0) {
            return {
              code: res.status,
              msg: res.msg,
              data: null,
              count: 1,
            };
          } else {
            return {
              code: res.status,
              msg: res.msg,
              data: res.data.list,
              count: res.data.total,
            };
          }
        }
      },
      page: true, //开启分页
      method: "post",
      id: "reloadTable",
      cols: [
        [
          //表头
          {
            field: "bid",
            title: "id",
            width: 60,
            align: "center",
          },
          {
            field: "sid",
            title: "sid",
            width: 160,
            align: "center",
          },
          {
            field: "text",
            title: "描述",
            align: "center",
            width: 130,
          },
          {
            field: "url",
            title: "图标",
            align: "center",
            width: 150,
            event: "img",
            templet: "#img",
          },
          {
            field: "name",
            title: "管理员",
            align: "center",
            width: 130,
          },
          {
            field: "create_time",
            title: "创建时间",
            align: "center",
            width: 180,
            sort: true,
          },
          {
            field: "update_time",
            title: "更新时间",
            align: "center",
            width: 180,
            sort: true,
          },
          {
            fixed: "right",
            align: "center",
            field: "delState",
            title: "是否展示",
            width: 190,
            templet: "#display",
            unresize: true,
          },
          {
            fixed: "right",
            align: "center",
            title: "操作",
            toolbar: "#barDemo",
            width: 200,
          },
        ],
      ],
    });

    //监听行工具事件
    table.on("tool(table)", function (obj) {
      var data = obj.data;
      var id = data.bid;
      var url = data.url;
      if (obj.event === "img") {
        var img =
          "<img src='" +
          url +
          "' class='img' style='width:98%;margin-left: 5px;'>";
        var image = "<div class='" + "'id='" + "demo2" + "'>" + img + "</div>";
        layer.open({
          area: ["600px", "500px"],
          type: 1,
          title: "查看图片",
          value: url,
          content: image,
          btn: "关闭",
          yes: function (index) {
            layer.closeAll();
          },
        });
      }
      if (obj.event === "del") {
        layer.confirm(
          "真的要删除 id为" + id + " 的轮播图吗",
          {
            btn: ["确定", "取消"],
            title: "提示",
          },
          function (index) {
            $.post({
              url:  GlobalSiteUrl + "/img/deleteBanner?bid=" + id,
              success: function (res) {
                if (res.status == 200) {
                  layer.msg(res.msg);
                  layer.close(index);
                  setTimeout(function () {
                    location.reload();
                  }, 1000);
                } else {
                  layer.msg(res.msg, {
                    time: 1500,
                    anim: 6,
                  });
                  layer.close(index);
                }
              },
            });
            layer.close(index);
          }
        );
      } else if (obj.event === "edit") {
        type = "edit";
        console.log(type);
        bid = data.bid;
        layer.open({
          area: ["720px", "360px"],
          type: 1,
          title: "修改id为" + obj.data.bid + "的轮播图信息",
          content: $(".addPanel"),
          // btn: ["确定", "取消"],
          // yes: function (index) {
          //   var data = $(".addForm").serializeArray();
          // },
        });
      }
    });

    //按钮事件
    var $ = layui.$,
      active = {
        reload: function () {
          // 页面重载&模糊查询
          var search = $("#search");
          //执行重载
          table.reload(
            "reloadTable",
            {
              // header:'application/x-www-form-urlencoded',
              page: {
                curr: 1, //重新从第 1 页开始
              },
              where: {},
            },
            "data"
          );
        },
      };

    // 按键监听
    $(".demoTable .layui-btn").on("click", function () {
      var type = $(this).data("type");
      active[type] ? active[type].call(this) : "";
    });

    // 新增数据
    $(".add").on("click", function (res) {
      type = "add";
      layer.open({
        area: ["720px", "360px"],
        type: 1,
        title: "新增轮播图",
        content: $(".addPanel"),
        // btn: ["确定", "取消"],
        // yes: function (index) {
        //   var data = $(".addForm").serializeArray();
        // },
      });
    });

    $(".post").on("click", function (res) {
      var file = document.querySelector("input[type=file]").files.length;
      var FromData = $(".addForm").serializeArray();
      const text = FromData[0].value;
      const sid = FromData[1].value;
      if (type === "add") {
        if (text === "") {
          layer.msg("描述不能为空", {
            icon: 2,
            time: 1500,
          });
          return;
        } else if (sid === ""){
          layer.msg("id不能为空", {
            icon: 2,
            time: 1500,
          });
          return;
        } else if (file === 0) {
          layer.msg("请上传图片", {
            icon: 2,
            time: 1500,
          });
          return;
        }
      } else {
        if (file === 0 && text === "" && sid === "") {
          layer.msg("请至少修改一样", {
            icon: 2,
            time: 1500,
          });
          return
        } else {
          $.post({
            url: `${GlobalSiteUrl}/img/banner`,
            data: { bid, sid, type: "edit", suid, text},
            ContentType: "multipart/form-data",
            success: function (res) {
              if (res.status == 200) {
                layer.msg(res.msg, {
                  icon: 1,
                  time: 1500,
                });
                setTimeout(function () {
                  location.reload();
                }, 1000);
              } else {
                layer.msg(res.msg, {
                  icon: 2,
                  time: 1500,
                });
              }
            },
          });
          return;
        }
      }
    });

    // 是否展示
    form.on("checkbox(display)", function (obj) {
      console.log(obj);
      var delState = "";
      if (obj.elem.checked) {
        delState = 0;
      } else {
        delState = 1;
      }
      $.ajax({
        type: "POST",
        url:
          GlobalSiteUrl +
          "/img/banner?type=edit&delState=" +
          delState +
          "&bid=" +
          obj.value,
        success: function (res) {
          if (delState == 0) {
            layer.msg("展示成功");
          } else {
            layer.msg("取消展示");
          }
          location.reload()
        },
      });
    });
  });
})();
